package com.lyy.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;

/**
 * @author 俞伟
 * @version 1.0
 * @date 2020/7/30
 * @description com.tongsheng.system.utils
 */
@Slf4j
public class ImageUtil {
    /**
     * <p>Title: thumbnailImage</p>
     * <p>Description: 根据图片路径生成缩略图 </p>
     *
     * @param imagePath 原图片路径
     * @param w         缩略图宽
     * @param h         缩略图高
     * @param force     是否强制按照宽高生成缩略图(如果为false，则生成最佳比例缩略图)
     */
    public static InputStream thumbnailImage(InputStream imgFile, int w, int h, boolean force) {
        try {
            // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
            String types = Arrays.toString(ImageIO.getReaderFormatNames());
            log.debug("target image's size, width:{}, height:{}.", w, h);
            Image img = ImageIO.read(imgFile);
            if (null == img) {
                return null;
            }
            if (!force) {
                // 根据原图与要求的缩略图比例，找到最合适的缩略图比例
                int width = img.getWidth(null);
                int height = img.getHeight(null);
                if ((width * 1.0) / w < (height * 1.0) / h) {
                    if (width > w) {
                        h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0)));
                        log.debug("change image's height, width:{}, height:{}.", w, h);
                    }
                } else {
                    if (height > h) {
                        w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h / (height * 1.0)));
                        log.debug("change image's width, width:{}, height:{}.", w, h);
                    }
                }
            }
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.getGraphics();
            g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
            g.dispose();
            return FileUtils.bufferedImageToInputStream(bi);
        } catch (Exception e) {
            log.error("generate thumbnail image failed.", e);
            return null;
        }
    }

    /**
     * 生成缩略图
     *
     * @param picPath      图片地址
     * @param picSmallPath 缩略图地址
     */
    private static void makePic(String picPath, String picSmallPath) {
        File file = new File(picPath);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        InputStream in = thumbnailImage(inputStream, 100, 100, false);
        FileUtils.writeToLocal(picSmallPath, in);
    }
}